// remote.js
// invoke remote interface using ssh tunnel
import axios from 'axios';
import API from '@/js/api';
import { ElMessage } from 'element-plus';

class RemoteAPI {
    constructor() {
        this.remoteId = -1;
        this.localBaseUrl = '';
        this.remoteName = '';
    }

    async setRemoteId(remoteId) {
        // 从远程获取对应的信息
        let result = await API.local.invoke('GetRemoteInfo', { remoteId: remoteId });
        // console.log(`remoteID = ${remoteId}, result = `, result);
        if (result.code == 0 && result.msg.ssh_status) {
            this.remoteId = remoteId;
            this.remoteName = result.msg.name;
            let src_port = result.msg.tunnel_src_port;
            this.localBaseUrl = `http://localhost:${src_port}`;
        } else {
            this.remoteId = -1;
            this.localBaseUrl = '';
        }
    }

    // 获取接口的get url地址（特别针对加载本地图片）
    api_url(method, params) {
        if (this.remoteId < 0) {
            console.error(`Error get api_url, Possible Remote Connection is not Ready!`);
            return '';
        } else {
            let base_url = `${this.localBaseUrl}/${method}`;
            let query = Object.entries(params)
                .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                .join('&');
            return `${base_url}?${query}`;
        }
    }

    // 通过 method（字符串）和 params 调用本地的 API 接口
    // 判断 window.electronAPI 是否可用，否则直接选择使用 Local Web Server
    async invoke(method, params) {
        if (this.remoteId < 0) {
            console.error(`Error invoking remote API, Possible Remote Connection is not Ready!`);
            return;
        } else {
            try {
                if (this.use_post_method) {
                    return await this._localPost(method, params);
                } else {
                    return await this._localGet(method, params);
                }
            } catch (error) {
                console.error('Error invoking remote API:', error.message);
                ElMessage.error('调用远程服务失败，错误信息：' + error.message);

                // 大概率是远程服务的连接断了，更新下状态
                await API.local.invoke('RemoteTest', { remoteId: this.remoteId });

                return { code: -1, msg: error.message };
            }
        }
    }

    // 发起 POST 请求
    async _localPost(method, params) {
        // console.log('this.localBaseUrl = ', this.localBaseUrl);
        try {
            const response = await axios.post(`${this.localBaseUrl}/${method}`, params);
            return response.data;
        } catch (error) {
            // console.error('Error invoking local API with POST:', error.message);
            throw error;
        }
    }

    // 发起 GET 请求
    async _localGet(method, params) {
        try {
            const response = await axios.get(`${this.localBaseUrl}/${method}`, {
                params,
                paramsSerializer: (params) => {
                    return Object.entries(params)
                        .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
                        .join('&');
                }
            });
            return response.data;
        } catch (error) {
            // console.error('Error invoking local API with GET:', error.message);
            // ElMessage.error('调用远程服务失败，错误信息：' + error.message);
            throw error;
        }
    }
}

export { RemoteAPI };
